import StandProductList from '@/components/product/StandProductList';
import StandProductSort, { SortFilter } from '@/components/product/StandProductSort';
import StandSearch from '@/components/StandSearch';
import utils from '@/utils';
import { View } from '@tarojs/components';
import classNames from 'classnames';
import React, { useCallback, useRef, useState } from 'react';
import styles from './index.module.scss';

const StandSearchProduct = ({
  className = '',

  // 搜索框属性
  searchProps: {
    defaultValue,
    onNext,

    autoFocus = true,
    ...searchRest
  } = {},

  // 排序属性, 如果属性 为 null / undefined, 不显示排序
  sortProps,

  // 显示商品的属性
  productProps: {
    list = [],
    isFinished,
    isLoading,

    // 100 为顶部搜索高度
    // 90 为 排序 高度
    // 24 为默认间隔高度
    height = utils.getCalcHeight({}, 100, !!sortProps ? 90 : 0, 24),

    ...productRest
  } = {},

  // 如果存在 children, 则 不会使用 sortProps 和 productProps,
  // 而是直接显示 children, 逻辑需要自己处理
  children,
}) => {
  const isShowSort = !!sortProps;

  const [sort, setSort] = useState(sortProps?.defaultValue ?? SortFilter.comprehensive);

  const searchValueRef = useRef(defaultValue);

  const [scrollTop, setScrollTop] = useState(0);
  const updateScrollTop = useCallback(() => {
    if (scrollTop === 0) {
      setScrollTop(0.0001);
    } else {
      setScrollTop(0);
    }
  }, [scrollTop]);

  return (
    <View
      className={classNames(`${styles.StandSearchProduct} ${className}`, {
        custom: !!children?.length,
        sort: !children?.length && isShowSort,
      })}
    >
      <StandSearch
        className="stand-search"
        onSearch={async ({ value }) => {
          searchValueRef.current = value;

          await onNext({
            page: 1,
            value,
            sort,
          });

          updateScrollTop();
        }}
        {...{
          autoFocus,
          ...searchRest,
        }}
      >
        {!children?.length && isShowSort && (
          <StandProductSort
            {...{
              value: sort,
              onChange: async (v) => {
                setSort(v);

                await onNext({
                  page: 1,
                  value: searchValueRef.current,
                  sort: v,
                });
              },
              ...sortProps,
            }}
          />
        )}

        {!children?.length && (
          <StandProductList
            {...{
              className: `stand-product-list ${isShowSort ? 'sort' : ''}`,

              height,
              scrollTop,

              list,
              isFinished,
              isLoading,

              onNext: () => {
                return onNext({
                  value: searchValueRef.current,
                  sort,
                });
              },

              ...productRest,
            }}
          />
        )}

        {!!children?.length && children}
      </StandSearch>
    </View>
  );
};

export default StandSearchProduct;
